package com.atguigu.tingshu.search.thread;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author：yyj
 * @Package：com.atguigu.tingshu.search.thread
 * @Project：tingshu_parent240829
 * @name：ExpireThread
 * @Date：2025/2/7 20:15
 * @Filename：ExpireThread
 */



public class ExpireThread {
    private volatile  boolean isStop=false;

    private RedisTemplate redisTemplate;

    public ExpireThread(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    HashMap<String, Thread> stringThreadHashMap = new HashMap<>();
    ReentrantLock reentrantLock = new ReentrantLock();

    public void Expire(String lockKey,Long interval,Long ttl){
        Thread expireThread = stringThreadHashMap.get("expire");
        reentrantLock.lock();
        if (expireThread==null){
            try {
                expireThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (!isStop){
                            try {
                                Thread.sleep(interval);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            System.out.println(Thread.currentThread().getName()+"开始续期");
                            redisTemplate.expire(lockKey,ttl, TimeUnit.SECONDS);
                        }
                    }
                });
                stringThreadHashMap.put("expire",expireThread);
                expireThread.setDaemon(true);//守护线程 jvm中没有线程则停止运行
                expireThread.setName("ExpireThread");
                expireThread.start();
            } finally {
                reentrantLock.unlock();
            }
        }else {
            expireThread.run();//其他抢到锁的进程继续执行run方法
        }
    }

    public void isStop() {
        isStop=true;
    }
}
